package com.deyuanyun.pic.pbf.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.deyuanyun.pic.common.cache.TempStoreDataSupport;
import com.deyuanyun.pic.common.util.CommonUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.RequestUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.pbf.app.domain.PbfLoginLog;
import com.deyuanyun.pic.pbf.app.domain.PbfResult;
import com.deyuanyun.pic.pbf.app.enumeration.FormCode;
import com.deyuanyun.pic.pbf.app.enumeration.PbfAppCode;
import com.deyuanyun.pic.pbf.app.service.PbfService;
import com.deyuanyun.pic.pbf.enumeration.ImgCustomType;
import com.deyuanyun.pic.settings.controller.dto.MyFileVO;
import com.deyuanyun.pic.settings.controller.dto.SMSMessageVO;
import com.deyuanyun.pic.settings.service.base.UploadService;
import com.deyuanyun.pic.settings.support.utils.SMSUtils;
import com.deyuanyun.pic.settings.task.Pool;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jerry
 * @Description 维修维护app控制器
 * @date 2016-06-16
 */
@Controller
@RequestMapping("/pbf/app")
public class PbfController {

    private Logger logger = LogManager.getLogger(this.getClass());

    @Resource
    private PbfService pbfService;

    @Resource
    private UploadService uploadService;

    @Value("${File_Server_Path}")
    String fileServerPath;//文件服务器地址

    @RequestMapping("/getUserName")
    @ResponseBody
    public void getUserName(String Param, HttpServletResponse rep) {
        PbfResult pbfResult = new PbfResult();
        JSONObject obj = JSON.parseObject(Param);
        if (ObjectUtil.isEmptyAll(obj)) {
            sendAppMessage(pbfResult, PbfAppCode.PARAMETER_FAIL.getCode(), PbfAppCode.PARAMETER_FAIL.getLabel(), rep);
            return;
        }
        String account = obj.getString("Account").trim();
        try {
            PbfResult result = pbfService.getUserName(account);
            AjaxResponse.sendText(rep, JSON.toJSONString(result));

        } catch (Exception e) {
            logger.error(e);
            sendAppMessage(pbfResult, PbfAppCode.SERVICE_FAIL.getCode(), PbfAppCode.SERVICE_FAIL.getLabel(), rep);
        }
    }

    @RequestMapping("/loginApp")
    @ResponseBody
    public void login(String Param, HttpServletResponse rep) {
        PbfResult pbfResult = null;
        try {
            pbfResult = pbfService.login(Param);
            AjaxResponse.sendText(rep, JSON.toJSONString(pbfResult));
        } catch (Exception e) {
            sendAppMessage(pbfResult, PbfAppCode.SERVICE_FAIL.getCode(), PbfAppCode.SERVICE_FAIL.getLabel(), rep);

            PbfLoginLog loginLog = JSON.parseObject(Param, PbfLoginLog.class);
            loginLog.setId(CommonUtil.getUUID());
            loginLog.setCreateDate(new Date());
            loginLog.setState(1);
            pbfService.insertErrLog(loginLog);

            logger.error(e);
        }

    }

    /**
     * 发送验证码
     *
     * @param phone
     * @param response
     * @throws Exception
     */
    @RequestMapping("/getVerifyCode")
    @ResponseBody
    public void sendLoginCaptchaSms(String phone, HttpServletResponse response) throws Exception {
        Asserts.assertTrue(org.apache.commons.lang.StringUtils.isNotEmpty(phone), "手机号码不能为空");
        phone = phone.trim();
        Asserts.assertTrue(StringUtils.isMobile(phone), "手机号码非法");

        String p1 = TempStoreDataSupport.pullData("sms_" + phone);
        Asserts.assertTrue(org.apache.commons.lang.StringUtils.isBlank(p1), "发送频率过快，请稍后重试");

        //判断系统号码存不存在
        String sms = SMSUtils.makeLoginCaptchaMsg(phone);
        SMSMessageVO vo = new SMSMessageVO();
        vo.setMessage(sms);
        vo.setType("login");
        vo.setPhone(phone);
        Pool.SMS_QUEUE.put(vo);
        PbfResult pbfResult = new PbfResult();
        sendAppMessage(pbfResult, PbfAppCode.CAPTCHA_SUCCESS.getCode(), PbfAppCode.CAPTCHA_SUCCESS.getLabel(), response);
    }


    @RequestMapping("/logoutApp")
    @ResponseBody
    public void getlogputApp(String Param, HttpServletRequest request, HttpServletResponse rep) {
        PbfResult pbfResult = new PbfResult();
        sendAppMessage(pbfResult, PbfAppCode.SUCCESS.getCode(), PbfAppCode.SUCCESS.getLabel(), rep);
        request.getSession().removeAttribute("App_User_");
        // SecurityUtils.removeUser(request);
        // org.apache.shiro.SecurityUtils.getSubject().logout();

    }

    //获取配置
    @RequestMapping("/getConfigs")
    @ResponseBody
    public void getConfigs(String Param, HttpServletResponse response) {
        // this.checkUser(Param,response);
        PbfResult pbfResult = new PbfResult();
        try {
            pbfResult.setCode(PbfAppCode.SUCCESS.getCode());
            pbfResult.setMsg(PbfAppCode.SUCCESS.getLabel());
            Map<String, Object> map = pbfService.getConfigs();
            pbfResult.setResult(map);
            AjaxResponse.sendText(response, JSON.toJSONString(pbfResult));
        } catch (Exception e) {
            logger.error(e);
            sendAppMessage(pbfResult, PbfAppCode.SERVICE_FAIL.getCode(), PbfAppCode.SERVICE_FAIL.getLabel(), response);
        }


    }

    //获取维修维护项目列表
    @RequestMapping("/getProjects")
    @ResponseBody
    public void getProjects(String Param, HttpServletResponse response) {
        this.checkUser(Param, response);
        Map<String, Object> map1 = new HashMap<String, Object>();
        try {
            Map<String, Object> result = pbfService.getProjects(Param);
            map1.put("Code", PbfAppCode.SUCCESS.getCode());
            map1.put("Msg", PbfAppCode.SUCCESS.getLabel());
            if (ObjectUtil.isNotNullEmpty(result)) {
                map1.put("Result", result);
            }
            String jsonResult = JSON.toJSONString(map1);
            AjaxResponse.sendText(response, jsonResult);

        } catch (Exception e) {
            logger.error(e);
            sendAppMessage(map1, PbfAppCode.SERVICE_FAIL.getCode(), PbfAppCode.SERVICE_FAIL.getLabel(), response);
        }
    }

    //获取缺陷点列表
    @RequestMapping("/getDefects")
    @ResponseBody
    public void findDefectList(HttpServletResponse response, String Param) {
        this.checkUser(Param, response);
        Map<String, Object> map1 = new HashMap<String, Object>();
        try {
            Map<String, Object> result = pbfService.findDefectList(Param);
            map1.put("Code", PbfAppCode.SUCCESS.getCode());
            map1.put("Msg", PbfAppCode.SUCCESS.getLabel());
            if (ObjectUtil.isNotNullEmpty(result)) {
                map1.put("Result", result);
            }
            String jsonResult = JSON.toJSONString(map1, SerializerFeature.DisableCircularReferenceDetect);
            System.out.println(jsonResult);
            AjaxResponse.sendText(response, jsonResult);


        } catch (Exception e) {
            sendAppMessage(map1, PbfAppCode.SERVICE_FAIL.getCode(), PbfAppCode.SERVICE_FAIL.getLabel(), response);
            logger.error(e);
        }
    }

    //添加新缺陷点
    @RequestMapping("/addDefect")
    @ResponseBody
    public void addorUpdateDefect(String Param, HttpServletResponse response) {
        this.checkUser(Param, response);
        PbfResult pbfResult = new PbfResult();
        try {
            pbfResult.setCode(PbfAppCode.SUCCESS.getCode());
            pbfResult.setMsg(PbfAppCode.SUCCESS.getLabel());
            pbfService.addorUpdatePipeBodyDefect(Param);
            AjaxResponse.sendText(response, JSON.toJSONString(pbfResult));
        } catch (MalformedURLException e) {
            logger.error("<======调用webservice失败==========>", e);
        } catch (Exception e) {
            logger.error(e);
            sendAppMessage(pbfResult, PbfAppCode.SERVICE_FAIL.getCode(), PbfAppCode.SERVICE_FAIL.getLabel(), response);
        }

    }

    //删除缺陷点（此接口通过用做删除审核不通过的非内检缺陷）
    @RequestMapping("/delDefect")
    @ResponseBody
    public void delDefect(String Param, HttpServletResponse response) {
        this.checkUser(Param, response);
        PbfResult pbfResult = null;
        try {
            pbfResult = pbfService.delPipeBodyDefect(Param);
            AjaxResponse.sendText(response, JSON.toJSONString(pbfResult));
        } catch (Exception e) {
            logger.error(e);
            sendAppMessage(pbfResult, PbfAppCode.SERVICE_FAIL.getCode(), PbfAppCode.SERVICE_FAIL.getLabel(), response);
        }

    }

    //提交表单
    @RequestMapping("/postForm")
    @ResponseBody
    public void postForm(String Param, HttpServletResponse response) {
        this.checkUser(Param, response);
        PbfResult pbfResult = new PbfResult();
        try {
            pbfService.postForm(Param);
            sendAppMessage(pbfResult, PbfAppCode.SUCCESS.getCode(), PbfAppCode.SUCCESS.getLabel(), response);
        } catch (Exception e) {
            logger.error("<======提交表单失败==========>", e);
            sendAppMessage(pbfResult, PbfAppCode.SERVICE_FAIL.getCode(), PbfAppCode.SERVICE_FAIL.getLabel(), response);
        }
    }

    /**
     * 上传附件
     *
     * @param multipartFiles
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/uploadAppFile", method = RequestMethod.POST)
    @ResponseBody
    public void saveUploadFile(@RequestParam(value = "file", required = false) MultipartFile[] multipartFiles, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map param = RequestUtil.parseRequestParamToHashMap(request);
        String businessId = param.get("HostID").toString();//关联ID
        String repairType = param.get("Type").toString();//照片修复前中后
        String hostType = param.get("HostType").toString();//是否是缺陷点照片还是表单照片
        String formType = param.get("FormType").toString();//表单类型id
        FormCode formCode = FormCode.getVal(formType);
        MyFileVO fileVO = new MyFileVO();
        PbfResult result = new PbfResult();
        //TODO app端和bs端关于照片分类统一问题
        if ("Form".equals(hostType) && (FormCode.TRENCH_EXCAVATION.equals(formCode)
                || FormCode.CORROSION_ENVIRONMENT.equals(formCode)
                || FormCode.COAT_SURVEY.equals(formCode)
                || FormCode.SURFACE_TREATMENT.equals(formCode)
                || FormCode.CP_SURVEY.equals(formCode)
                || FormCode.CTRL_EXINSP.equals(formCode)
                || FormCode.DEFECT_MEASURE.equals(formCode)
                || FormCode.TRENCH_BACKFILL.equals(formCode)
                || FormCode.WELD_REPAIR.equals(formCode)) && "1".equals(repairType)) {
            fileVO.setType(ImgCustomType.ALL.toString());
        } else {
            fileVO.setType(ImgCustomType.REPAIR_BEFORE.toString());
        }

        if ("Form".equals(hostType)) {
            if ("2".equals(repairType)) {
                fileVO.setType(ImgCustomType.REPAIR_DURING.toString());
            } else if ("3".equals(repairType)) {
                fileVO.setType(ImgCustomType.REPAIR_AFTER.toString());
            } else if ("4".equals(repairType)) {
                fileVO.setType(ImgCustomType.NDTTYPE.toString());
            } else if ("5".equals(repairType)) {
                fileVO.setType(ImgCustomType.WELDWORKTYPE.toString());
            }
            if (org.apache.commons.lang.StringUtils.isBlank(fileVO.getType())) {
                sendAppMessage(result, PbfAppCode.UPLOAD_FAIL.getCode(), PbfAppCode.UPLOAD_FAIL.getLabel(), response);
                return;
            }
        } else {//新增缺陷点
            fileVO.setType(ImgCustomType.UPLOAD_IMAGE.toString());
        }
        fileVO.setBusinessId(businessId);
        if (multipartFiles == null || multipartFiles.length == 0) {
            sendAppMessage(result, PbfAppCode.UPLOAD_FAIL.getCode(), PbfAppCode.UPLOAD_FAIL.getLabel(), response);
            return;
        }
        String res = uploadService.saveStorageFile(multipartFiles[0], fileVO);
        String id = org.apache.commons.lang.StringUtils.substringBetween(res, "[", "]");
        String path = org.apache.commons.lang.StringUtils.substringBetween(res, "{", "}");
        if (org.apache.commons.lang.StringUtils.isNotBlank(path)) {
            result.setCode(PbfAppCode.UPLOAD_SUCCESS.getCode());
            result.setMsg(PbfAppCode.UPLOAD_SUCCESS.getLabel());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("Url", fileServerPath+path);
            map.put("Id",id);
            result.setResult(map);
            AjaxResponse.sendText(response, JSON.toJSONString(result));
        }

    }


    /**
     * 验证是否是合法用户
     *
     * @param Param
     * @param rep
     */

    private void checkUser(String Param, HttpServletResponse rep) {
        JSONObject obj = JSON.parseObject(Param);
        Map mapMarks = new HashMap();
        if (ObjectUtil.isEmptyAll(obj)) {
            sendAppMessage(mapMarks, PbfAppCode.PARAMETER_FAIL.getCode(), PbfAppCode.PARAMETER_FAIL.getLabel(), rep);
            return;
        }
        String userId = obj.getString("UserID");
        if (userId == null) {
            sendAppMessage(mapMarks, PbfAppCode.PARAMETER_FAIL.getCode(), PbfAppCode.PARAMETER_FAIL.getLabel(), rep);
            return;
        }
        if (pbfService.findUserId(userId) == null) {
            sendAppMessage(mapMarks, PbfAppCode.USER_FAIL.getCode(), PbfAppCode.USER_FAIL.getLabel(), rep);
            return;
        }
        return;
    }

    /**
     * 封装向app发送消息函数
     *
     * @param obj   对象
     * @param code  code编码
     * @param label 对应消息
     */
    private void sendAppMessage(Object obj, String code, String label, HttpServletResponse rep) {
        if (obj instanceof Map) {
            ((Map) obj).put("Code", code);
            ((Map) obj).put("Msg", label);
            AjaxResponse.sendText(rep, JSON.toJSONString(obj));
            return;
        }
        if (obj instanceof PbfResult) {
            ((PbfResult) obj).setCode(code);
            ((PbfResult) obj).setMsg(label);
            AjaxResponse.sendText(rep, JSON.toJSONString(obj));
        }
    }


}
